package com.scores.service.impl;

import com.scores.mapper.ScoreMapper;
import com.scores.pojo.Score;
import com.scores.pojo.ThreeS;
import com.scores.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class ScoreServiceImpl implements ScoreService {

    @Autowired
    ScoreMapper scoreMapper;

    @Override
    public int getScoreCount(String name) {
        if(name!=null && !name.isEmpty()) {
            name = "%" + name.trim() + "%";
        }
        return scoreMapper.getScoreCount(name);
    }

    @Override
    public List<ThreeS> getAllScoresByPage(String name, Integer page, Integer size) {
        if(name!=null && !name.isEmpty()) {
            name = "%" + name.trim() + "%";
        }
        if(page == null || size == null){
            return scoreMapper.getAllScoresByPage(name, null, null);
        }else{
            return scoreMapper.getAllScoresByPage(name, (page - 1) * size, size);
        }

    }

    @Override
    public int updateScore(ThreeS threeS) {
        List<Score> scoreList = scoreMapper.getScoreByStnoAndSuid(threeS.getStudentNo(), threeS.getSubjectId());
        if(scoreList != null && !scoreList.isEmpty()) {
            return 2; // Student already has a score for this subject
        }
        int count = scoreMapper.updateScore(threeS);
        if(count>0){
            return 0;
        }
        return 1;
    }

    @Override
    public int addScore(Score score) {
        List<Score> scoreList = scoreMapper.getScoreByStnoAndSuid(score.getStudentId(), score.getSubjectId());
        if(scoreList != null && !scoreList.isEmpty()) {
            return 2; // Student already has a score for this subject
        }
        int count = scoreMapper.addScore(score);
        if(count>0){
            return 0;
        }
        return 1;
    }

    @Override
    public int deleteScore(Integer scoreId) {
        int count = scoreMapper.deleteScore(scoreId);
        if(count>0) {
            return 0;
        }
        return 1;
    }

    @Override
    public List<ThreeS> getTotalScore() {
        return scoreMapper.getTotalScore();
    }

    @Override
    public List<ThreeS> getScoreByStudentNo(Integer studentNo, Integer page, Integer limit) {
        if(page == null || limit == null) {
            return scoreMapper.getScoreByStudentNo(studentNo, null, null);
        }
        return scoreMapper.getScoreByStudentNo(studentNo, (page - 1) * limit, limit);
    }
}
